import axios from 'axios';
import { useAxios } from '@vueuse/integrations/useAxios';
import { useTokenStore } from '@/stores/token';
import { message } from 'ant-design-vue';

import sysConfig from '@/config'

// Create axios instance
function request(config) {
    const instance = axios.create({
        baseURL: import.meta.env.VITE_APP_API_BASEURL,
        timeout: 5000,
        headers: { 'Content-Type': 'application/json' },
        withCredentials: true
    });

    // Request interceptor
    instance.interceptors.request.use(
        (config) => {
            const tokenStore = useTokenStore();
            if (tokenStore.isLogin && config.needToken === true) {
                config.headers.Authorization = sysConfig.TOKEN_PREFIX + tokenStore.token;
            }
            return config;
        },
        (error) => {
            return Promise.reject(error);
        }
    );

    // Response interceptor
    instance.interceptors.response.use(
        (response) => {
            return response;
        },
        (error) => {
            console.log(error);
            message.error(error.response.data.non_field_errors || error.response.data.detail || error.message);
            return Promise.reject(error);
        }
    );
    const { execute } = useAxios(instance)
    return execute(config.url, { ...config })
}

export default request